<template>
  <div>
    <div id="WeeklyEnergyChart" style="width: 100%; height: 330px;"></div>
  </div>
</template>

<script setup>
import { deviceDataService } from "@/services";
import { inject, onMounted, reactive, onUnmounted } from "vue";
import { defineProps } from 'vue';

const $echarts = inject("echarts");
const props = defineProps(['deviceId']);
const data = reactive({
  weeklyTimestamp: [],
  weeklyEnergyConsumptionData: [],
});
const charts = {};

onMounted(async () => {
  await fetchWeeklyData();
  initWeeklyChart();
  window.addEventListener("resize", resizeCharts);
});

onUnmounted(() => {
  window.removeEventListener("resize", resizeCharts);
  disposeCharts();
});

async function fetchWeeklyData() {
  try {
    const response = await deviceDataService.getWeekDataService(props.deviceId);
    setData(response.data.time_series_data);
  } catch (error) {
    console.error("Error fetching weekly data:", error);
  }
}

function setData(timeSeriesData) {
  // 获取最近七天的日期
  const today = new Date();
  const dates = [];
  for (let i = 6; i >= 0; i--) {
    const date = new Date(today);
    date.setDate(today.getDate() - i);
    dates.push(`${date.getMonth() + 1}/${date.getDate()}`);
  }

  data.weeklyTimestamp = dates;
  data.weeklyEnergyConsumptionData = timeSeriesData.map(item => item[props.deviceId].total_ele_quantity / 1000); // Assuming total_ele_quantity is in Wh, convert to 度
}

function initWeeklyChart() {
  const chartElement = document.getElementById("WeeklyEnergyChart");
  if (!chartElement) return;
  
  let myChart = $echarts.init(chartElement);
  
  myChart.setOption({
    title: {
      text: '周用电量',
      left: 'center',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#00FFFF',
      },
    },
    grid:{
      left: '15%',
    }
    ,
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
      backgroundColor: 'rgba(0, 0, 0, 0.7)',
      borderColor: '#fff',
      borderWidth: 1,
      textStyle: {
        color: '#fff',
      },
      formatter: function(params) {
        let result = params[0].name + '<br/>';
        params.forEach(item => {
          result += item.marker + item.seriesName + ': ' + item.value.toFixed(2) + ' 度<br/>';
        });
        return result;
      },
    },
    xAxis: {
      type: 'category',
      data: data.weeklyTimestamp,
      axisLabel: {
        color: '#00FFFF',
      },
      axisLine: {
        lineStyle: {
          color: '#333',
        },
      },
      axisTick: {
        show: false,
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} 度',
        color: '#00FFFF',
      },
      axisLine: {
        lineStyle: {
          color: '#333',
        },
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)',
        },
      },
    },
    series: [{
      name: '用电量',
      type: 'line',
      smooth: true,
      data: data.weeklyEnergyConsumptionData,
      lineStyle: {
        width: 2,
        color: 'rgba(0, 255, 255, 1)',
      },
      areaStyle: {
        color: new $echarts.graphic.LinearGradient(0, 0, 0, 1, [{
          offset: 0,
          color: 'rgba(0, 255, 255, 0.5)',
        }, {
          offset: 1,
          color: 'rgba(0, 255, 255, 0.1)',
        }]),
        opacity: 0.3,
      },
    }],
  });

  charts["WeeklyEnergyChart"] = myChart;
}

function resizeCharts() {
  for (let chart in charts) {
    if (charts[chart]) {
      charts[chart].resize();
    }
  }
}

function disposeCharts() {
  for (let chart in charts) {
    if (charts[chart]) {
      charts[chart].dispose();
      charts[chart] = null;
    }
  }
}
</script>
<style scoped>

</style>